package com.youlin.security;

import com.youlin.dto.Status;
import com.youlin.untils.RedisUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private String active;
    private RedisTemplate<String, Object> redisTemplate;
    //拦截的url
    private final static String LOGINPATTERN = "/login";
    private final static String HTTPMETHOD = "POST";

    public MyAuthenticationFilter(String active, RedisTemplate<String, Object> redisTemplate) {
        super(new AntPathRequestMatcher(LOGINPATTERN, HTTPMETHOD));
        this.active = active;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (active.equals("prod")) {
            HttpServletRequest req = (HttpServletRequest) request;
            if(LOGINPATTERN.equals(req.getServletPath()) && HTTPMETHOD.equalsIgnoreCase(req.getMethod())){
                String smsTel = req.getParameter("smsTel");
                Integer smsCode = Integer.valueOf(req.getParameter("smsCode"));
                Integer redisCode = RedisUtil.getObject(redisTemplate, "adminTel:" + smsTel, Integer.class);
                if (redisCode == null) {
                    request.setAttribute("status", Status.CODEINVALID);
                    request.getRequestDispatcher("/common/smsCodeError").forward(request, response);
                    return;
                }
                if (!redisCode.equals(smsCode)) {
                    request.setAttribute("status", Status.CODEERROR);
                    request.getRequestDispatcher("/common/smsCodeError").forward(request, response);
                    return;
                }
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws AuthenticationException, IOException, ServletException {
        return null;
    }
}
